//获取文章评论
//首先获取文章对应id
// location.search;
// new URLSearchParams 实例化方法快速获取路径中的查询字符串中的某个键的值
// console.log(new URLSearchParams(location.search).get("id"));
let id = new URLSearchParams(location.search).get("id");
// 封装为函数
function show() {
  //获取文章评论
  $.ajax({
    type: "get",
    url: `/api/articles/${id}/comments`,
    success: (res) => {
      if (res.status === 0) {
        //遍历
        let str = "";
        $.each(res.data, (index, item) => {
          let time = item.cdate;
          let newtime = time.substring(0, 10);
          console.log();
          str += `
        <div class="kr_comment_card">
        <div class="img-wrap">
          <img src="./uploads/avatar_3.jpg" alt="">
        </div>
        <div class="info">
          <p>${item.uname}<span>${newtime}</span></p>
          <p>${item.content}</p>
        </div>
        <a href="javascript:;" class="like">1</a>
        </div>
        `;
        });
        $(".talking").append(str);
      }
    },
  });
}
show();
//输入修改字数
$(".content").on("input", function () {
  console.log(123123);
  $(".form .action .other").text($(this).val().length);
});

//发表评论
$(".form").on("submit", function (e) {
  e.preventDefault();
  //判断,不能输入空值
  let uname = $(".uname").val();
  let content = $(".content").val();
  console.log(Boolean(uname));
  if (!uname) {
    alert("用户名不能为空");
    return;
  } else if (!content) {
    alert("评论内容不能为空");
    return;
  } else {
    //获取数据
    let data = $(this).serialize();
    $.ajax({
      type: "post",
      url: `/api/articles/${id}/comments`,
      data,
      success: (res) => {
        alert("评论成功");
        // 重刷新;
        show();
        //刷新成功清空输入框文本框的值
        $(".uname").val("");
        $(".content").val("");
        $(".form .action .other").text(0);
      },
    });
  }
});
